package vn.appsmobi.ui;

import vn.appsmobi.AlertDialogManager;
import vn.appsmobi.R;
import vn.appsmobi.activity.BaseActivity;
import vn.appsmobi.loader.AppDetailLoader;
import vn.appsmobi.loader.AppDetailLoader.Result;
import vn.appsmobi.loader.BaseLoader;
import vn.appsmobi.model.AppInfo;
import vn.appsmobi.ulti.ImageLoadOption;
import vn.appsmobi.ulti.LocalAppManager;
import vn.appsmobi.ulti.Log;
import vn.appsmobi.widget.EmptyLoadingView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.nostra13.universalimageloader.core.ImageLoader;

public class DetailFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<AppDetailLoader.Result>
{
  static final int APP_DETAIL_LOADER = 0;	
  protected String mAppId;  
  protected String mAppName = "";
  protected String mAppAgency = "";
  protected String mAppIconLink 	= "";
  protected String mAppCategory 	= "";
  protected Float mAppSize = 0F;
  private AppInfo mAppInfo;
  private LinearLayout mBaseView;
  protected AppDetailBottomBar mBottomBar;
  private View mContentView;
  protected TextView mDeveloper; 
  protected TextView mUpdateDate;
  protected TextView mVersion;
  protected AppDetailView mExtraDetailView;
  protected EmptyLoadingView mLoadingView;
  private TextView mName;
  private TextView mCategory;
  private String mPackageName;
  protected RatingBar mRatingBar;
  protected TextView mSize;	
  private ImageView mIcon;
  private boolean isRun = false;
  
  private ViewSwitcher.ViewFactory mIconViewFactory = new ViewSwitcher.ViewFactory()
  {
    public View makeView()
    {
      ImageView img = new ImageView(DetailFragment.this.getActivity());
      img.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
      return img;
    }
  };
  
	public DetailFragment()
	{		 
		super();
	}
    public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
    {
    	
        View view = paramLayoutInflater.inflate(R.layout.app_details, paramViewGroup, false);
        this.mContentView = view.findViewById(R.id.container);
	    //this.mContentView.setPadding(0, 0, 0, UiUtils.getSplitActionMenuHeight(this));
	    this.mBaseView = ((LinearLayout)view.findViewById(R.id.base_view));
	   // this.mBaseView.setVisibility(View.GONE);
	    this.mIcon = ((ImageView)view.findViewById(R.id.icon));
	    ImageLoader.getInstance().displayImage(DetailFragment.this.mAppIconLink,this.mIcon, ImageLoadOption.options);
	  
	    this.mName = ((TextView)view.findViewById(R.id.name));
	    this.mCategory = ((TextView)view.findViewById(R.id.cate_name));	    
	    this.mRatingBar = ((RatingBar)view.findViewById(R.id.ratingbar));
	    this.mSize = ((TextView)view.findViewById(R.id.size));
	    this.mDeveloper = ((TextView)view.findViewById(R.id.developer));
	    this.mExtraDetailView = ((AppDetailView)view.findViewById(R.id.extra_view));
	    this.mExtraDetailView.setVisibility(View.GONE);
	    this.mBottomBar 	= (AppDetailBottomBar) view.findViewById(R.id.bottom_bar);
	    this.mLoadingView 	= ((EmptyLoadingView)view.findViewById(R.id.loading));
	    this.mVersion 		= (TextView)view.findViewById(R.id.version);
	    this.mUpdateDate	= (TextView)view.findViewById(R.id.update_date);
	    this.mName.setText(this.mAppName);
	    this.mCategory.setText(this.mAppCategory);
	    this.mSize.setText(String.format("%.2f", this.mAppSize));
	    this.mDeveloper.setText(this.mAppAgency);
	    
        return view;
    }
    
    public static void setAppInfo(DetailFragment fragment,AppInfo appinfo)
    {
    	fragment.mAppInfo = appinfo;
    }
    
    private AppInfo.AppInfoUpdateListener mUpdateListener = new AppInfo.AppInfoUpdateListener()
	  {
	    public void onContentUpdate(final AppInfo appinfo)
	    {
	    	DetailFragment.this.getActivity().runOnUiThread(new Runnable()
		      {
		        public void run()
		        {
		        	Log.v("DetailFragment onContentUpdate:" + appinfo.getName());
		        	//Toast.makeText(DetailFragment.this.getActivity(),"DetailFragment onContentUpdate:" + appinfo.getName(), Toast.LENGTH_LONG).show();
		        	DetailFragment.this.updateViewContent(appinfo);
		        }
		      });
	    }

	    public void onStatusUpdate(final AppInfo appinfo)
	    {
	    	DetailFragment.this.getActivity().runOnUiThread(new Runnable()
		      {
		        public void run()
		        {
		        	//Toast.makeText(DetailFragment.this.getActivity(),"DetailFragment onStatusUpdate:"  + appinfo.getName(), Toast.LENGTH_LONG).show();
		        	DetailFragment.this.updateViewStatus(appinfo);
		        	Log.v("DetailFragment onStatusUpdate:" + appinfo.getName());
		        }
		      });
	    }
	  };

	  
	  protected void updateViewContent(AppInfo appinfo)
	  {	    
	    this.mExtraDetailView.updateViewContent(appinfo,true);
	    this.mBottomBar.updateViewContent(appinfo);		      
	  	this.mExtraDetailView.updateViewContent(appinfo, true);
	  	this.mExtraDetailView.setVisibility(View.VISIBLE);
	  	this.mRatingBar.setRating(appinfo.getRateNum());
	  	this.mName.setText(appinfo.getName());
	    this.mCategory.setText(appinfo.getCategory());
	    this.mSize.setText(String.format("%.2f", appinfo.getSize()));
	    this.mDeveloper.setText(appinfo.getCompanyName());
	    ImageLoader.getInstance().displayImage(appinfo.getIconLink(),this.mIcon, ImageLoadOption.options);
	    ((BaseActivity)DetailFragment.this.getActivity()).setBarTitle(appinfo.getName());
	  }
	  private void updateViewStatus(AppInfo appinfo)
	  {                     
	    if (!TextUtils.isEmpty(appinfo.getId()))
	      this.mBottomBar.updateActionButton(appinfo);
	  }
    
    
    public void onActivityCreated(Bundle paramBundle)
    {
        super.onActivityCreated(paramBundle);
        getLoaderManager().initLoader(APP_DETAIL_LOADER, null, this);
        // initLoader(CATEGORY_LOADER,null,this,getLoaderManager());
    }
    
    @Override
    public void onStart(){
    	Log.v("onStart");
        super.onStart();
        if (this.mAppInfo != null)
            this.mAppInfo.addUpdateListener(this.mUpdateListener);
        else
        	Log.v("mAppInfo null");
    }
  
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		
		super.onResume();		
		if(mAppInfo != null)
		{
			this.mBottomBar.updateViewContent(mAppInfo);
			this.mExtraDetailView.updateViewContent(mAppInfo, true);
			this.mExtraDetailView.setVisibility(View.VISIBLE);
		}
		
	}
	@Override
    public Loader onCreateLoader(int id, Bundle bundle) {
        Log.v("onCreateLoader called");
        if (id == APP_DETAIL_LOADER)
        {
            this.mLoader = new AppDetailLoader(getActivity()); 
            if(this.mAppId != null)
            	((AppDetailLoader)this.mLoader).setAppDetailID(this.mAppId);
            else if(this.mPackageName != null)
            	((AppDetailLoader)this.mLoader).setAppDetailID(this.mPackageName);
            
            this.mLoader.setProgressNotifiable(this.mLoadingView);
        }
        BaseLoader baseLoader = this.mLoader;
        return baseLoader;
    }


	@Override
	public void onLoadFinished(Loader<Result> loader,final Result data) {
		DetailFragment.this.getActivity().runOnUiThread(new Runnable()
	    {
	      public void run()
	      {
	    	Log.v("Detail onLoadFinished");
	    	LocalAppManager.getManager().loadInstalledApps(false);
	    	//DetailFragment.setAppInfo(DetailFragment.this, data.mAppDetailInfos);	 
	    	if(data != null){
	    		mAppInfo = AppInfo.get(data.mAppDetailInfos.getId());
		  		mAppInfo.addUpdateListener(mUpdateListener);
		  		updateViewContent(mAppInfo);
		  		updateViewStatus(mAppInfo);
		  		Log.v("autoRun:" + isRun);
		  		if(isRun)
		  			mBottomBar.MiddleClick();
	    	}else{
	    		AlertDialogManager alert = new AlertDialogManager();
	    		alert.showAlertDialog(getActivity(),getString(R.string.Error), getString(R.string.text_error_unknown),false, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						getActivity().onBackPressed();
						
					}
				});
	    	}
	    	
	  		
	      }
	    });

	}


	@Override
	public void onLoaderReset(Loader<Result> loader) {
		// TODO Auto-generated method stub
		
	}
    
	public void setAppId(String appid)
	{
		this.mAppId = appid;
	}
	
	public void setAppName(String appname)
	{
		this.mAppName = appname;
	}
    
	public void setAppAgencty(String appAgency)
	{
		this.mAppAgency = appAgency;
	}
	
	public void setAppIcon(String appIcon)
	{
		this.mAppIconLink = appIcon;
	}
	
	public void setAppCat(String cat)
	{
		this.mAppCategory = cat;
	}
    
	public void setAppSize(Float size)
	{
		this.mAppSize = size;
	}
	
	public void setPackageName(String packagename)
	{
		this.mPackageName = packagename;
	}
	
	public void setAutoRun(boolean auto){
		
		this.isRun = auto;
		Log.v("autoRun11111111111111111111111:" + isRun);
	}
}